package com.hiruss.efair.persistence;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.hiruss.efair.entities.Advertisement;

/**
 * 
 * @author Hiru
 */
public class AdvertisementManager {

	public void addAdvertisement(Advertisement ad) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(ad);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			pm.close();
		}

	}

	public List<Advertisement> getAllAdvertisements() {

		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<Advertisement> results = new ArrayList<Advertisement>();
		try {
			Query query = pm.newQuery("select from "
					+ Advertisement.class.getName());

			results = new ArrayList<Advertisement>(
					(List<Advertisement>) query.execute());
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			pm.close();
		}
		return results;
	}

	public List<Advertisement> getAdvertisementsByCategory(String category) {

		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<Advertisement> results = new ArrayList<Advertisement>();
		try {
			Query query = pm.newQuery("select from "
					+ Advertisement.class.getName()
					+ " where category == categoryParam "
					+ "parameters String categoryParam");

			results = new ArrayList<Advertisement>(
					(List<Advertisement>) query.execute(category));
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			pm.close();
		}
		return results;
	}

	public List<Advertisement> getAdvertisementsByKeyWord(String key) {

		key = key.toLowerCase().replaceAll("[^a-z0-9]", "");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<Advertisement> results = new ArrayList<Advertisement>();
		try {
			Query query = pm.newQuery("select from "
					+ Advertisement.class.getName());
			List<Advertisement> tempResults = (List<Advertisement>) query
					.execute();
			for (Advertisement ad : tempResults) {
				if (ad.getItem().toLowerCase().replaceAll("[^a-z0-9]", "")
						.indexOf(key) != -1
						|| ad.getDescription().toLowerCase()
								.replaceAll("[^a-z0-9]", "").indexOf(key) != -1
						|| ad.getCategory().toLowerCase()
								.replaceAll("[^a-z0-9]", "").indexOf(key) != -1)
					results.add(ad);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			pm.close();
		}
		return results;
	}
}
